// counter: action + reducer

// 将定义了所有 Action Type 的对象导入
import constants from '../../app/constants';
// 将对象结构后赋值给指定的变量
const { COUNTER_INCREMENT , COUNTER_DECREMENT } = constants ;

// action creator
export const increment = payload => {
  // 返回一个新的 action 实例
  return { type: COUNTER_INCREMENT , payload };
}

// action creator
export const decrement = payload => {
  return { type: COUNTER_DECREMENT , payload };
}

// 定义初始状态
const initState = { 
  value: 0 
}

// 定义 Reducer
const counterReducer = ( state = initState , action )=>{
  let newState ;
  switch( action.type ) {
      case COUNTER_INCREMENT :
          // Object.assign( target , ...soruces )
          // Object.assign( {} , 原始状态 , 被修改的部分 )
          newState = Object.assign( {} , state , { value: state.value + 1 } );
          return newState ;
      case COUNTER_DECREMENT :
          // Object.assign( {} , 原始状态 , 被修改的部分 )
          newState = Object.assign( {} , state , { value: state.value - 1 } );
          return newState ;
      default:
          return state ;
  }
}

export const selectCount = state => state.counter.value;

// 默认导出
export default counterReducer ;